const app = getApp()

Page({
    data: {
        xPageReady : true ,
        bgColor:[],
        bgColorS:[],
        user: [
            
          { cn: '我觉得很难让自己安静下来', key: 'hard_calm_down', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"],step:1 },
          { cn: '我感到口干舌燥', key: 'feel_dry', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"],step:1  },
          { cn: '我好像一点都没有感觉到任何愉快、舒畅', key: 'happy_comfortable', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"],step:1 },
          { cn: '我感到呼吸困难(例如：气喘或透不过气来)', key: 'dyspnea', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"], step:1},
          { cn: '我感到很难主动去开始工作', key: 'active_work', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"],step:1 },
          { cn: '我对事情往往做出过敏反应', key: 'anaphylaxis', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"],step:1 },
          { cn: '我感到颤抖（例如，手抖）', key: 'tremble', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"],step:1 },
          { cn: '我觉得自己消耗了很多精力', key: 'burn_out', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"], step:1},
          { cn: '我担心一些可能让自己恐慌或出丑的场合', key: 'panic_occasion', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"],step:1 },
          { cn: '我觉得自己对不久的将来没有什么可期盼的', key: 'no_expectations', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"],step:1 },
          { cn: '我感到忐忑不安', key: 'very_upset', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"], step:1},
          { cn: '我感到很难放松自己', key: 'relax_yourself', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"], step:1},
          { cn: '我感到忧郁沮丧', key: 'melancholy_depression', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"], step:1},
          { cn: '我无法容忍任何阻碍我继续工作的事情', key: 'melancholy_depression', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"], step:1},
          { cn: '我感到快要崩溃了', key: 'collapse', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"], step:1},
          { cn: '我对任何事情都不能产生热情', key: 'generate_enthusiasm', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"], step:1},
          { cn: '我觉得自己不怎么配做人', key: 'unworthy_being_man', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"],step:1 },
          { cn: '我发觉自己很容易被触怒', key: 'offended', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"],step:1 },
          { cn: '即使在没有明显的体力活动时,我也感到心律不正常', key: 'physical_activity', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"],step:1 },
          { cn: '我无缘无故地感到害怕', key: 'feel_afraid', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"], step:1},
          { cn: '我感到生命毫无意义', key: 'meaning_life', value: '', type: 'picker2', range: ["不符合", "有时符合", "常常符合", "总是符合"],step:1 },
        
          { cn: '入睡时间(关灯后到睡着的时间)', key: 'sleep_delay', value: '', num_type:1, type: 'picker2', step:'2',range: [ '没问题','轻微延迟', '显著延迟', '延迟严重或没有睡觉'], }, 
          { cn: '夜间苏醒', key: 'sleep_interruption_night', value: '', num_type:1,type: 'picker2', step:'2', range: [ '没问题','轻微影响', '显著影响', '严重影响或没有睡觉'], }, 
          { cn: '比期望的时间早醒', key: 'wake_early', value: '', num_type:1,type: 'picker2',  step:'2',range: [ '没问题','轻微提早', '显著提早', '严重提早或没有睡觉'], }, 
          { cn: '总睡眠时间 ', key: 'sleep_time', value: '',num_type:1, type: 'picker2', step:'2', range: [ '足够','轻微不足', '显著不足', '严重不足或没有睡觉'], }, 
          { cn: '总睡眠质量(无论睡多长)', key: 'sleep_quality_evaluation', value: '',num_type:1, type: 'picker2', step:'2', range: [ '满意','轻微不满', '显著不满', '严重不满或没有睡觉'], }, 
          { cn: '白天情绪', key: 'daytime_mood', value: '', type: 'picker2', num_type:1, step:'2',range: [ '正常','轻微低落', '显著低落', '严重低落'], },
          { cn: '白天身体功能(体力或精神：如记忆力、认知力和注意力等)', key: 'daytime_body_function', value: '',num_type:1, type: 'picker2',  step:'2',range: [ '足够','轻微影响', '显著影响', '严重影响'], }, 
          { cn: '白天思睡', key: 'sleepiness_during_day', value: '',num_type:1, type: 'picker2', step:'2', range: [ '无思睡','轻微思睡', '显著思睡', '严重思睡'], },

          { cn: '你的名字（或昵称）', key: 'real_name', value: '', type: 'text', step:3}, // 真实姓名
          { cn: '出生日期', key: 'birthday', value: '', type: 'date' , step:3}, // 出生日期
          { cn: '性别', key: 'sex', value: '', type: 'picker', range: ["男", "女"], step:3 }, // 性别
          { cn: '工作', key: 'work', value: '', type: 'picker', range: ["就业中", "待业中", "上学"], step:3 }, // 工作
          { cn: '婚恋状态', key: 'marriage_love_state', value: '', type: 'picker', range: ["未婚", "已婚", "离异"] , step:3}, 
          { cn: '受教育程度', key: 'education', value: '', type: 'picker', range: ["小学", "初中", "高中", "中专", "大专", "本科", "硕士", "博士"], step:3 },
          { cn: '疼痛病史和诊断治疗经历（300字以内）', key: 'diagnostic_experience', value: '', type: 'textarea', step:3},
            
        ],
        first:1,
        check1:false,
        check2:false,
        check3:false,
        check4:false,
        needSetting:app.globalData.needAuthorization
    },
    onLoad: function (options) {
      let that =this;
     
      that.xInit()
        
    },
    
    xInit: async function () {
        let that = this
        let user = that.data.user

        await wx.cloud.callFunction({
            name: "user",
            data: {
                action: "detail"
            }
        }).then(res => {
            let data = res.result
            // for(var i in data){
            //     for(var j in user){
            //         if(user[j].key === i){
            //             // console.log(user[j].key)
            //             user[j].value = data[i]
            //         }
            //     }
            // }
            // for(let index in res.result.drugs_being_taken){
            //   if(res.result.drugs_being_taken[index]=='非甾体类(如阿司匹林、布洛芬、塞来西布等)'){
            //     that.setData({
            //       check1:true
            //     })
            //   }
            //   if(res.result.drugs_being_taken[index]=='阿片类(如芬太尼、曲马多、吗啡等)'){
            //     that.setData({
            //       check2:true
            //     })
            //   }
            //   if(res.result.drugs_being_taken[index]=='抗惊厥类(如安定、加巴喷丁、普瑞巴林等)'){
            //     that.setData({
            //       check3:true
            //     })
            //   }
            //   if(res.result.drugs_being_taken[index]=='抗抑郁类(如阿米替林、度洛西汀、文拉法辛等)'){
            //     that.setData({
            //       check4:true
            //     })
            //   }
            // }

            that.setData({
                user : user
            })
            for(let index in that.data.user){
              if(that.data.user[index].value>=0){
                that.data.bgColor.push('linear-gradient(to right, #D3F9CC 30%, #F2E5BF 60%, #F2CFD4 100%)')
                that.data.bgColorS.push('linear-gradient(to right,#23E201 30%,#FFBB00 60%,#FF4F66 100%)')
              }else{
                that.data.bgColor.push('#eee')
                that.data.bgColorS.push('linear-gradient(to right, #23E201 30% ,#FFBB00 60%, #FF4F66 100%)')
              }
              
            }
            that.setData({
              bgColor:that.data.bgColor,
              bgColorS:that.data.bgColorS
            })
            
        })

        that.setData({
            xPageReady : false
        })
    },
    checkboxChange(e) {
      let that = this
      let value = e.detail.value
      let params = e.currentTarget.dataset
      that.setData({
          [`user[${params.idx}].value`]: value
      })
    },
    xregion:function(e){
      let that = this
      let value =' '
      if(e.detail.value[0] !==  e.detail.value[1]){
        value  = e.detail.value[0]+ e.detail.value[1] 
      }else{
        value = e.detail.value[0]
      }
      let params = e.currentTarget.dataset
      that.setData({
          [`user[${params.idx}].value`]: value
      })
    },
    sliderchange:function(e){
      let that = this
      let value = e.detail.value
      let params = e.currentTarget.dataset
      that.setData({
        [`user[${params.idx}].value`]: value,
        [`bgColor[${params.idx}]`]:'linear-gradient(to right, #D3F9CC 30%, #F2E5BF 60%, #F2CFD4 100%)'
      })
      if(e.detail.value<=(params.max/5)){
        that.setData({
          [`bgColorS[${params.idx}]`]:'linear-gradient(to right,#23E201 50%,#97E201 100%)'
        })
      }else if( e.detail.value> (params.max/5)&& e.detail.value <= (params.max/5)*3){
        that.setData({
          [`bgColorS[${params.idx}]`]:'linear-gradient(to right,#23E201 50%,#FFBB00 100%)'
        })
      }else{
        that.setData({
          [`bgColorS[${params.idx}]`]:'linear-gradient(to right,#23E201 30%,#FFBB00 60%,#FF4F66 100%)'
        })
      }
    },
    xInput: function (e) {
        let that = this
        let value = e.detail.value
        let params = e.currentTarget.dataset
        that.setData({
            [`user[${params.idx}].value`]: value
        })
    },
    choose:function(e){
      let that = this
      let params = e.currentTarget.dataset
      if(that.data.user[params.idx].num_type===1){
        that.setData({
          [`user[${params.idx}].value`]: params.i+1
        })
      }else{
        that.setData({
            [`user[${params.idx}].value`]: params.value
        })
      }
    },

    xPicker: function (e) {
        let that = this
        let sel = e.detail.value
        let params = e.currentTarget.dataset
        let range = that.data.user[params.idx].range
        let value = range[sel]
        that.setData({
            [`user[${params.idx}].value`]: value
        })
    },

    xDate: function (e) {
        let that = this
        let value = e.detail.value
        let params = e.currentTarget.dataset
        that.setData({
            [`user[${params.idx}].value`]: value
        })
    },
    handleTouchInput:function(){
      this.setData({
        innerShow:true
      })
    },
    changePrivacySetting:function(e){
      this.setData({
        needSetting:false
      })
    },
    xPhone: async function (e) {
        let that = this
        let params = e.currentTarget.dataset
        wx.showLoading({
            title: '请稍等',
        })
        await wx.cloud.callFunction({
            name: 'user',
            data: {
                action: 'getPhone',
                cloudID: e.detail.cloudID
            },
            success: function (res) {
                that.setData({
                    [`user[${params.idx}].value`]: res.result.phoneNumber
                })
            }
        })

        wx.hideLoading()

    },

    xLocation: async function (e) {
        let that = this
        let params = e.currentTarget.dataset

        // wx.showLoading({
        //     title: '请稍等',
        // })

        // await wx.getLocation({
        //     type: 'wgs84',
        //     success(res) {
        //         const latitude = res.latitude
        //         const longitude = res.longitude
        //         const speed = res.speed
        //         const accuracy = res.accuracy
        //         wx.request({
        //             url: `https://apis.map.qq.com/ws/geocoder/v1/?key=CQ3BZ-OXQKP-7RLDJ-L4FP5-VLIIH-ENFXZ&location=` + latitude + ',' + longitude,
        //             success: res => {
        //                 let address = res.data.result.address_component
        //                 let city = address.city
        //                 let area = address.district
        //                 that.setData({
        //                     [`user[${params.idx}].value`]: city + '-' + area
        //                 })
        //             }
        //         })
        //     }
        // })

        wx.hideLoading()

    },
      // 66
    xTonext:function(){
      let that =this;
      let key =0
      for (let i in that.data.user) {
        if (that.data.user[i].value === '' && that.data.user[i].key!='diagnostic_experience' && that.data.user[i].step== that.data.first) {
            key=key+1
        }
      }
      if(key>0){
        var firstQ = ''
        for (var i =0;i<that.data.user.length;i++) {
          if (that.data.user[i].value === '') {
            firstQ=i
            break;
          }
        }
        wx.showModal({
          title: "提示",
          content: "请确保所有内容填写正确，当前有"+ key +"项内容未填写，请检查！",
          showCancel: false,
          confirmText:'好的',
          success (res) {
            if (res.confirm) {
              wx.pageScrollTo({
                selector: '#selector'+firstQ,
              })
            }
          }
        })
        return
      }
      this.setData({
        first:this.data.first+1
      })
      wx.pageScrollTo({
        scrollTop: 0,
      })
    },
    xChildReload: function () {
      var pages = getCurrentPages();//当前页面栈
      if (pages.length > 1) {
        var beforePage = pages[pages.length - 2];//获取上一个页面实例对象
        beforePage.xInfo();//触发父页面中的方法
      }
    },
    xSubmit: function () {
        let that = this
        let user = that.data.user
        let key =0
        for (let i in that.data.user) {
          if (that.data.user[i].value === '' && that.data.user[i].key!='diagnostic_experience' && that.data.user[i].step== that.data.first) {
              key=key+1
          }
        }
        if(key>0){
          var firstQ = ''
          for (var i =0;i<that.data.user.length;i++) {
            if (that.data.user[i].value === '') {
              firstQ=i
              break;
            }
          }
          wx.showModal({
            title: "提示",
            content: "请确保所有内容填写正确，当前有"+ key +"项内容未填写，请检查！",
            showCancel: false,
            confirmText:'好的',
            success (res) {
              if (res.confirm) {
                wx.pageScrollTo({
                  selector: '#selector'+firstQ,
                })
              }
            }
          })
          return
        }
        wx.showLoading({
          title: '保存中',
        })
        that.xUpload(user)
    },

    xUpload: function (data) {
        let that =this;
        let form = {}
        for (var i = 0; i < data.length; i++) {
            if (data[i].value !== '') {
                form[data[i].key] = data[i].value
            }
        }
        wx.cloud.callFunction({
            name: "user",
            data: {
                action: "edit",
                formdata: form
            }
        }).then(res => {
            wx.showToast({
                title: '保存成功',
                icon: 'none',
                success: () => {
                    setTimeout(() => {
                      wx.navigateBack({
                        delta: 1,
                      })
                      that.xChildReload()
                    }, 1000)
                }
            })
        })
    }
})